//定义对象
var platformLoginRecord = {
		/**
	     * 初始化
	     * */
		init : function(){
			  this.sliderH(); 
		      /** 初始化日期 * */
			  this.initPlatformList();
			  this.initQueryTime();
			  this.winH ="";
			  this.sliderH = "";
			  this.mapH ="";
			  this.bindQuery();
			  this.initTable();
			  this.myChart=this.initBarChart();
			  this.mydoubleChart=this.initDoubleBarChart();
			  //默认查询
			  $("#queryLoginRecord").trigger("click");
		},
		 /**
	     * 计算各div高度的高度
	     * */
    sliderH : function(){
    	var _this=this;
    	_this.winH = $(window).height();
    	_this.sliderH = _this.winH - 58;
    	_this.mapH = _this.sliderH-50;
        $('#tableDiv').height(_this.mapH);
    },
    getToday : function(){
		var todayDate = new Date();
        var yyyy = todayDate.getFullYear();
        var mm = todayDate.getMonth()+1;
        var dd = todayDate.getDate();  
        if (mm.toString().length == 1) {
	        mm = '0' + mm;
	    }
	    if (dd.toString().length == 1) {
	        dd = '0' + dd;
	    }
        return yyyy + '-' + mm + '-' + dd;
	},
    initQueryTime:function(){//默认时间
        var todayDate = new Date();
        var todayDateStr=todayDate.getFullYear()+"-"+(todayDate.getMonth()+1)+"-"+todayDate.getDate();  
        	
        var beforeDate = new Date(todayDate); 
	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
	    if (mm.length == 1) {
	        mm = '0' + mm;
	    }
	    if (dd.length == 1) {
	        dd = '0' + dd;
	    }
        $("#inputStartDate").val(yyyy + '-' + mm + '-' + dd);
        $("#inputEndDate").val(yyyy + '-' + mm + '-' + dd);
      },
    /**
     * 获取平台列表
     */
    initPlatformList:function(){
    	var me=this;
		$.ajax({
			type : 'post',
			url : appCtx + "log/platformLoginRecord/queryPlatform.html",
			cache : false,
			dataType : "JSON",
			success : function(data) {
				if(data!=null&&data!=''){
					$('#platformDiv').html("<select class='query-select' id='platformIdSel'></select>");
					var selectStr="";
					//selectStr+="<option value=''>请选择平台</option>";
					$.each(data,function(entryIndex,entry) {
						selectStr+="<option value='"+entry.gnss_centerid+"'>"+entry.text+"</option>";
					});
					$('#platformIdSel').html(selectStr);
					$("#platformIdSel").select2();					
				}
			}
		});
	},
	//初始化柱状图
	initBarChart: function(){
		var me = this;
		//计算显示的柱子数
		var percent = 100;

		option = {
			title:{text:'平台连通率',x:'center',textStyle:{fontSize:'14px'} },
		    color: ['#4F81BD'],
		    tooltip : {
		        trigger: 'axis',
		        show: true,
		        axisPointer : {            // 坐标轴指示器，坐标轴触发有效
		        	show: true,
		            type : 'line'        // 默认为直线，可选为：'line' | 'shadow'
		        },
		    },
		    grid: {
		        left: '10px',
		        top:'13%',
		        bottom: '3%',
		        containLabel: true
		    },
		    xAxis : [
		        {
		            type : 'category',
		            data : [],
		            name: '',
		            axisTick: {
		                alignWithLabel: true
		            },
		            axisLabel:{
		            	textStyle: {
                            fontSize: 10
                        }
		            }
		        }
		    ],
		    yAxis : [
		        {
		            	type : 'value',
			            name: '单位:%',
			            min:0,
			            max:100,
			            minInterval: 1,
		        }
		    ],
		    series : [
		        {
		        	name:'连通率',
		            type:'bar',
		            smooth:true,
		            itemStyle: {normal: {areaStyle: {type: 'default'}}},
		            data:[0],
		            barMaxWidth:'40px',
		            areaStyle:{normal: {color:"#66CD00"}},
		            lineStyle:{normal: {color:"#00E5EE"}},
		        }
		    ],
		};
            var myChart = echarts.init(document.getElementById('barChart'));
            myChart.setOption(option);
            window.onresize = myChart.resize;
            myChart.on('click', function(param){
            	var today=me.today[param.dataIndex];
            	me.showDoubleBarChart(today);
            });
            return {
            	refash : function(option){
                    myChart.setOption(option);
            	},
            	option : option,
            	barChartDom : myChart
            };        
	},
	initDoubleBarChart: function(){
		var me = this;
		//计算显示的柱子数
		var percent = 100;
		option = {
				title:{text:'登录时间分布',x:'center',textStyle:{fontSize:'14px'} },
			    tooltip : {
			        trigger: 'axis',
			        formatter: '{b0}'
			    },
			    legend: {
			        data:[]
			    },
			    toolbox: {
			        
			    },
			    grid: {
			        left: '10px',
			        top:'13%',
			        right:10,
			        bottom: '3%',
			        containLabel: true
			    },
			    calculable : true,
			    xAxis : [
			        {
			            type : 'category',
			            boundaryGap : false,
			            data : [],
			        }
			    ],
			    yAxis : [
			        {
			            type : 'value',
			            name: '',
			            min:0,
			            max:2,
			            minInterval: 1,
			             axisLabel:{
			                    formatter: function (value, index) {
			                     var texts = [];
			                        if (index === 0) {
			                            texts.push('断开');
			                        }
			                        if (index === 2) {
			                            texts.push('连接');
			                        }
			                        return texts;
			                    }
			                }
			        }
			    ],
			    series : [
			        {
			            name:'链路状态',
			            type:'line',
			            step: 'end',
			            data:[0]
			        }
			    ]
			};
		 	var mydoubleChart = echarts.init(document.getElementById('doubleBarChart'));
	        mydoubleChart.setOption(option);
	        window.onresize = mydoubleChart.resize;
	        return {
	        	refash : function(option){
	        		mydoubleChart.setOption(option);
	        	},
	        	option : option,
	        	barChartDom : mydoubleChart
	        };         
	},
	showBarChart:function(){
		var me = this;
		var	gnsscenterId = $("#platformIdSel").val();
		var startTime = $("#inputStartDate").val();
		var endTime = $("#inputEndDate").val();
		$.ajax({
			url:appCtx+"log/platformLoginRecord/getPlatformLoginRecordList.html",
			type:"post",
			async : true,
			cache : false,
			data:{
				startTime:startTime,
				endTime:endTime,
				gnsscenterId:gnsscenterId
			},
			dataType:"json",
			success:function(datas){
					/*初始化条形图*/
				var xis = new Array();
				var series1 = new  Array();
				var today = new  Array();
					var area_name=null;
					$.each(datas,function(index,vo){
						xis.push(vo.id);
						series1.push(Math.round(vo.online_rate*Math.pow(10,2))/Math.pow(10,2));
						today.push(vo.analyse_date);
					});
					var options = me.myChart.option;
					options.xAxis[0].data=xis;
					options.series[0].data=series1;
					me.today=today;
					me.myChart.refash(options);   
			}
		});
	},
	
	showDoubleBarChart:function(today){
		var me = this;
		var startTime =null;
		var endTime = null;
		var	gnsscenterId = $("#platformIdSel").val();
		if(today!=null && today!=''){
			var beforeDate = new Date(today); 
    	    var yyyy = beforeDate.getFullYear(), mm = (beforeDate.getMonth() + 1).toString(), dd = beforeDate.getDate().toString();
    	    if (mm.length == 1) {
    	        mm = '0' + mm;
    	    }
    	    if (dd.length == 1) {
    	        dd = '0' + dd;
    	    }
			startTime = yyyy + '-' + mm + '-' + dd;
			endTime = yyyy + '-' + mm + '-' + dd;
		}else{
			startTime = $("#inputStartDate").val();
			endTime = $("#inputEndDate").val();
		}
		$.ajax({
			url:appCtx+"log/platformLoginRecord/showLineChart.html",
			type:"post",
			async : true,
			cache : false,
			data:{
				startTime:startTime,
				endTime:endTime,
				gnsscenterId:gnsscenterId
			},
			dataType:"json",
			success:function(datas){
				if(datas.length==0){
					var dataRows= {
    			     		rows:'',
    			     		total:0,
    			     		page:1
    			     	};
					$("#loginRecordList").flexAddData(dataRows);
				}else{
					var dataRows= {
    			     		rows:datas,
    			     		total:datas.length,
    			     		page:1
    			     	};
    		     	$("#loginRecordList").flexAddData(dataRows);
				}
					/*初始化条形图*/
				var xis = new Array();
				var series1 = new  Array();
				var series2 = new  Array();
					var area_name=null;
					$.each(datas,function(index,vo){
						xis.push((vo.timeStr).substring(10));
						if ( vo.main_link_state == 0  && vo.sub_link_state == 0) {
							series1.push(1);
					  	  }else{
					  		  series1.push(0);
					  	  }
					});
					var options = me.mydoubleChart.option;
					options.xAxis[0].data=xis;
					options.series[0].data=series1;
					if(datas.length!=0){
						options.title.text=datas[0].id+"登录时间分布";
					}else{
						options.title.text="登录时间分布";
					}
					me.mydoubleChart.refash(options);   
			}
		});
	},

    /**
     * 初始化表格
     * */
    initTable:function(){
			    /**
				 * 判断是否登录成功
				 */
			    var getConfirm = function (main_link_state, sub_link_state){
			  	  var out = "断开" ;
			  	  if ( main_link_state == 0  && sub_link_state == 0) {
			  		  out = "连接" ;
			  	  }
			  	  return out;
			    };
		    	$("#loginRecordList").flexigrid(
		    			{
	                dataType: 'json',
		            colModel : [{
		            	display : '平台名称',
		                name : 'id',
		                width : 40,
		                sortable : false,
		                align : 'left',
		            },{
		                display : '链路状态',
		                name : 'isSuccess',
		                width : 20,
		                sortable : false,
		                align : 'left', 
		                 paramcolnames:["main_link_state","sub_link_state"],
		                handlefunction:getConfirm
		            },{
		                display : '发生时间',
		                name : 'timeStr',
		                width : 40,
		                sortable : false,
		                align : 'left',
		                showTitle: "timeStr"
		            }],
		        	resizable: false,
		            sortname: "timeStr",// 第一次加载数据时排序列
		            sortorder: "desc",// 第一次加载数据时排序类型
		            usepager: false,// 是否分页，默认为true。
		            showToggleBtn: false,
		            showTableToggleBtn: false,// 是否显示收起/打开按钮,默认不显示。
		            useRp: true,// 是否可以动态设置每页显示的结果数，默认为false。
		            rp: 10000,// 每页记录数，默认为10
		            rpOptions: [10, 20, 50, 100, 200], // 每页结果数
		            singleSelect: true,
		            width : $('#tableDiv').width(),// 表格宽度
		            widthType: '%',
		            height :nav.whiceH[1]-20,
			            titDisplay: false,
			     
			     });  	
	   },
	   
	    /**
	     * 弹出导出选择页
	     */
	    exportSimCard: function () {
	    	var me = this;
	    	var	gnsscenterId = $("#platformIdSel").val();
	    	var startTime = $("#inputStartDate").val();
	        var endTime = $("#inputEndDate").val();
	        var options = $("#loginRecordList").getOptions();
	        var total = options.total;
	        if (total == 0) {
	            global.ajaxLoading.pop("无导出数据", false, 2000);
	            return;
	        }
	        var pages = options.pages;
	        var options = $("#loginRecordList").getOptions();
	        //总记录数
	        var total = options.total;
	        //每页大小
	        var pagesize = options.rp;
	        global.ajaxLoading.pop("正在导出,请稍后.....", true, 2000);
	        //获取导出的参数
	        var exportParams = options.exportParams;
	        if ( total > 60000) {
	        	global.ajaxLoading.pop("最多只能导出60000条数据", true, 2000);
	            return;
	        }
	        var columns = platformLoginRecord.getColumn();
	        var header1 = JSON.stringify(columns);
	        var colModelList = new Array();//表头
	        colModelList.push(header1);
	        var colModel = $.toJSON(colModelList);
	        var paramsGrid = {
	           colModel: colModel,
	            title: "平台登录日志",
	            imgsrc: null,
	            startTime:startTime+" 00:00:00",
				endTime:endTime+" 23:59:59",
				gnsscenterId:gnsscenterId
	        };
	        post(appCtx + "log/platformLoginRecord/exportPlatformLoginRecord.html", paramsGrid);
	    },
	    /**
	     * 获取表格字段头
	     */
	    getColumn: function() {
	    	return [{
            	display : '平台名称',
                name : 'id',
                width : 200,
                sortable : false,
                align : 'center',
            },{
                display : '链路状态',
                name : 'isSuccess',
                width : 200,
                sortable : false,
                align : 'center', 
            },{
                display : '发生时间',
                name : 'timeStr',
                width : 300,
                sortable : false,
                align : 'center',
            }];
	    },
	   /**
	    * 事件触发查询
	    */
	    bindQuery: function () {
	    	var _this = this;
	        $("a[name='exportSimCardBtn']").bind('click', function () {
	        	platformLoginRecord.exportSimCard();
	        });
	        $("#confirmExport").click(function () {
	        	platformLoginRecord.exportComfirm();
	        })
	        $('#queryLoginRecord').click(function () {
	            // 查询不能超过三十天
	            var start = $("#inputStartDate").val().replace(/-/g, "/");
	            var end = $("#inputEndDate").val().replace(/-/g, "/");
	            if ((new Date(end).getTime() - new Date(start).getTime()) / (1000 * 60 * 60 * 24) > 30) {
	                global.ajaxLoading.pop("查询不能超过三十天", false, 1000);
	                return;
	            }
	            var inputStartDate = $("#inputStartDate").val();
	    		var inputEndDate = $("#inputEndDate").val();
	    		var today = _this.getToday();
	            if(inputStartDate == inputEndDate && inputStartDate == today){
	    			$("#chartDiv").hide();
	    			$("#tableDiv").css('margin-top','0px');
	    			$("#tableDiv .bDiv").height(nav.whiceH[1]-20+'px');
	    			
	    		}else{
	    			$("#chartDiv").show();
	    			$("#tableDiv").css('margin-top','20px');
	    			$("#tableDiv .bDiv").height(nav.whiceH[1]-260+'px');
	    		}
	            _this.showBarChart();
	            _this.showDoubleBarChart();
	        });
	    },

}
/**
 * 初始化
 * */
platformLoginRecord.init();
